package com.wy.framework.actions.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.Action;
import com.wy.framework.actions.AbstractBaseAction;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.services.common.FileService;
import com.wy.framework.services.login.LoginService;
import com.wy.framework.services.org.OrgManageService;
import com.wy.framework.services.user.UserManageService;
import com.wy.component.dataConvert.DateUtil;
import com.wy.component.dataConvert.JsonUtil;
import com.wy.component.image.ImageUtil;

/**
 * 项目名称：openportal
 * 类名称：FileUploadAction
 * 类描述：上传文件通用控制器
 * 创建人：张旭星
 * 创建时间：2015-12-28 下午7:38:07
 * 修改人：张旭星
 * 修改时间：2015-12-28 下午7:38:07
 * 版本信息：@version 1.0
 * Copyright (c) 2015万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
public class FileUploadAction extends AbstractBaseAction {
	private List<Map> rows;
	
	private List resultList;
	
	private int participants;
	
	private int meetDeptQty;
	
    private static final long serialVersionUID = 1L;

    private static Logger logger = LoggerFactory.getLogger(FileUploadAction.class);

    @Autowired
    private FileService fileService;
    
    @Autowired
	private UserManageService userManageService;
    
    @Autowired
    private OrgManageService orgManageService;
    
    @Autowired
    private LoginService loginService;

    /**
     * 文件名
     */
    private String fileName;

    /**
     * 经转换后实际存储的文件名
     */
    private String fileDiskName;

    /**
     * 文件大小(KB为单位)
     */
    private String fileSize;

    /**
     * 文件的业务类型(如附件、模板)
     */
    private String type;
    /**
     * 允许的文件类型
     */
    private String allowedType;

    /**
     * 允许的文件类型
     */
    private File file;

    private Map<String, String> params = new HashMap<String, String>();
    
	private String jsonRes;

    private String init(boolean excelCheckFlag) throws ServiceException, IOException {
    	logger.info("文件上传开始");
    	MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
    	// 文件名
    	fileName = req.getFileNames("file")[0];
    	fileName = fileName.replaceAll("%", "％").replaceAll("'", "‘").replace(" ", "").replace(" ", "");
    	// 允许的文件类型
    	String allowedType = req.getParameter("allowedType");
    	// 文件的业务类型(如附件、模板)
    	String type = req.getParameter("type");
    	//允许大小
    	String allowedSize = req.getParameter("allowedSize");
    	file = req.getFiles("file")[0];
    	//报送数据类型必须为97-2003的excel
//    	if(excelCheckFlag){
//    		byte[] buffer = null;
//    		try {
//    			FileInputStream fi = new FileInputStream(file);
//    			ByteArrayOutputStream bos = new ByteArrayOutputStream();
//    			byte[] b = new byte[1024];
//    			int n;
//    			while((n=fi.read(b))!=-1){
//    				if(n>8)
//    					n=8;
//    				bos.write(b,0,n);
//    				break;
//    			}
//    			fi.close();
//    			bos.close();
//    			buffer = bos.toByteArray();
//    			if(!(buffer[0]==-48 && buffer[1]==-49 && buffer[2]==17 && buffer[3]==-32 && buffer[4]==-95 && buffer[5]==-79 && 
//    					buffer[6]==26 && buffer[7]==-31)){
//    				rspCode = RtnCodeConstant.RTN_CODE_A02_RPT_LOG_MIME_ERROR;
//    				rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_A02_RPT_LOG_MIME_ERROR);
//    				logger.error("文件上传失败:报送数据类型必须为97-2003的excel");
//    				file.delete();
//    				return Action.SUCCESS;
//    			}
//    		} catch (FileNotFoundException e1) {
//    			e1.printStackTrace();
//    		} catch (IOException e) {
//    			e.printStackTrace();
//    		}
//    	}
    	
    	//升级时额外备份,把之前版本的zip备份到_
    	String upgradeBackup = ServletActionContext.getRequest().getParameter("upgrade");
    	if(StringUtils.isNotEmpty(upgradeBackup)){
    		String oldFile = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "/upload/zip/" + ServletActionContext.getRequest().getParameter("functionId") + ".zip";;
    		String newFile = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "/upload/zip/" + ServletActionContext.getRequest().getParameter("functionId") + "_.zip";;
    		FileUtils.copyFile(new File(oldFile), new File(newFile));
    	}
    	
    	// 从页面传入的functionId
    	fileDiskName = ServletActionContext.getRequest().getParameter("functionId") + ".zip";
		
    	// 文件类型检查
//    	rspCode = fileService.fileTypeCheck(fileName, allowedType);
//    	if (!RtnCodeConstant.RTN_CODE_SUCCESS.equals(rspCode)) {
//    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR;
//    		rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_FILE_NOT_ALLOWED_ERROR, new String[] { allowedType });
//    		file.delete();
//    		return Action.SUCCESS;
//    	}
    	
    	long size = file.length();
    	fileSize = new DecimalFormat("0.00KB").format(size / 1024.0);
    	long maxSize;
    	if(StringUtils.isNotEmpty(allowedSize))
    		maxSize = Integer.parseInt(allowedSize) * 1024;//KB转为Byte
		else
			maxSize = new BigDecimal(fileService.getMaxSize()).longValue();
    	if (size > maxSize) {
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR;
    		rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR, new String[] { String.valueOf(maxSize/1024)+"KB" });
    		logger.error("文件上传失败:文件大小超限【" + String.valueOf(maxSize) + "】");
    		file.delete();
    		return Action.SUCCESS;
    	}
    	
    	// 空文件检查
    	if (size == 0) {
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_EMPTY_ERROR;
    		file.delete();
    		return Action.SUCCESS;
    	}
    	
//		String newFile = fileService.getFolder() + fileDiskName;
		String newFile = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "/upload/zip/" + fileDiskName;
		try {
			// 将文件拷贝到配置的目录
		    FileUtils.copyFile(file, new File(newFile));

//		    String fengMian = ServletActionContext.getRequest().getParameter("fengMian");
//	        BufferedImage sourceImg;
//			try {
//				sourceImg = ImageIO.read(new FileInputStream(file));
//				//非图片不处理
//				if(sourceImg!=null){
//					//封面图处理,缩小宽度到600满足页面编辑
//					if(StringUtils.isNotEmpty(fengMian)){
////					CommonUtil.imageResize(file.getPath(), newFile, 600, fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//					}
//					//其它图片拉大满足分享尺寸
//					else{
//						//宽 >= 高
//						if(sourceImg.getWidth() >= sourceImg.getHeight()){
//							if(sourceImg.getHeight() < 300){
//								ImageUtil.imageResize(file.getPath(), newFile, new Double(305d / sourceImg.getHeight() * sourceImg.getWidth()).intValue(), fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//							}
//						}
//						//宽 < 高
//						else{
//							if(sourceImg.getWidth() < 300){
//								ImageUtil.imageResize(file.getPath(), newFile, 305, fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//							}
//						}
//					}
//				}
//			} catch (FileNotFoundException e1) {
//				e1.printStackTrace();
//			} catch (IOException e1) {
//				e1.printStackTrace();
//			}
		} catch (IOException e) {
		    logger.error("拷贝文件失败 from:{},to{}", file.getAbsolutePath(), newFile);
		    logger.error(e.getMessage());
		    rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_ERROR;
		}
		logger.info("上传文件名:{},文件大小:{}", fileName, fileSize);
		return "";
	}
    
    /**
     * 用于zip上传
     * 
     * 实现功能 1.实现文件上传至服务器 2.文件类型检查(根据请求参数中的允许类型检查) 3.空文件监测
     * 4.将文件按类型拷贝至对应的目录(文件类型包含在请求参数中,文件名将改为包含UUID的文件名)
     * 5.上传文件初始保存路径,参考struts.xml配置项struts.multipart.saveDir 6.上传文件大小限制,
     * 参考struts.xml配置项struts.multipart.maxSize
     */
    @Override
	public String execute() throws ServiceException {
		try {
			if (StringUtils.equals(init(false), Action.SUCCESS))
				return Action.SUCCESS;
			file.delete();
		} catch (IOException e) {
			e.printStackTrace();
		}
//		jsonRes = "ok";
		return Action.SUCCESS;
    }
    
    public String fileUploadMportal() throws ServiceException {
    	logger.info("文件上传开始");
    	MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
    	// 文件名
    	fileName = req.getFileNames("file")[0];
    	fileName = fileName.replaceAll("%", "％").replaceAll("'", "‘").replace(" ", "").replace(" ", "");
    	// 允许的文件类型
    	String allowedType = req.getParameter("allowedType");
    	// 文件的业务类型(如附件、模板)
    	String type = req.getParameter("type");
    	//允许大小
    	String allowedSize = req.getParameter("allowedSize");
    	file = req.getFiles("file")[0];
    	// 物理文件名\文件大小将返回给前端
    	fileDiskName = fileService.getUniqueName(fileName);
    	// 文件类型检查
//    	rspCode = fileService.fileTypeCheck(fileName, allowedType);
//    	if (!RtnCodeConstant.RTN_CODE_SUCCESS.equals(rspCode)) {
//    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR;
//    		rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_FILE_NOT_ALLOWED_ERROR, new String[] { allowedType });
//    		file.delete();
//    		return Action.SUCCESS;
//    	}
    	
    	long size = file.length();
    	fileSize = new DecimalFormat("0.00KB").format(size / 1024.0);
    	long maxSize;
    	if(StringUtils.isNotEmpty(allowedSize))
    		maxSize = Integer.parseInt(allowedSize) * 1024;//KB转为Byte
		else
			maxSize = new BigDecimal(fileService.getMaxSize()).longValue();
    	if (size > maxSize) {
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR;
    		rspMsg = msgSourceAdapter.getMessage(RtnCodeConstant.RTN_CODE_FILE_UPLOAD_MAX_SIZE_ERROR, new String[] { String.valueOf(maxSize/1024)+"KB" });
    		logger.error("文件上传失败:文件大小超限【" + String.valueOf(maxSize) + "】");
    		file.delete();
    		return Action.SUCCESS;
    	}
    	
    	// 空文件检查
    	if (size == 0) {
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_EMPTY_ERROR;
    		file.delete();
    		return Action.SUCCESS;
    	}
    	
		// 将文件拷贝到配置的目录
		String newFile = fileService.getFolder() + fileDiskName;
		try {
		    FileUtils.copyFile(file, new File(newFile));
		    
		    //图片尺寸处理以满足于qq微信分享的尺寸要求
//		    String fengMian = ServletActionContext.getRequest().getParameter("fengMian");
//	        BufferedImage sourceImg;
//			try {
//				sourceImg = ImageIO.read(new FileInputStream(file));
//				//非图片不处理
//				if(sourceImg!=null){
//					//封面图处理,缩小宽度到600满足页面编辑
//					if(StringUtils.isNotEmpty(fengMian)){
////					CommonUtil.imageResize(file.getPath(), newFile, 600, fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//					}
//					//其它图片拉大满足分享尺寸
//					else{
//						//宽 >= 高
//						if(sourceImg.getWidth() >= sourceImg.getHeight()){
//							if(sourceImg.getHeight() < 300){
//								CommonUtil.imageResize(file.getPath(), newFile, new Double(305d / sourceImg.getHeight() * sourceImg.getWidth()).intValue(), fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//							}
//						}
//						//宽 < 高
//						else{
//							if(sourceImg.getWidth() < 300){
//								CommonUtil.imageResize(file.getPath(), newFile, 305, fileDiskName.substring(fileDiskName.lastIndexOf(".") + 1));
//							}
//						}
//					}
//				}
//			} catch (FileNotFoundException e1) {
//				e1.printStackTrace();
//			} catch (IOException e1) {
//				e1.printStackTrace();
//			}
		} catch (IOException e) {
		    logger.error("拷贝文件失败 from:{},to{}", file.getAbsolutePath(), newFile);
		    logger.error(e.getMessage());
		    rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_ERROR;
		}
		logger.info("上传文件名:{},文件大小:{}", fileName, fileSize);
		JSONObject j = new JSONObject();
		StringBuffer url = req.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();  
		j.put("path", tempContextUrl +"/upload/"+fileDiskName);
		jsonRes = j.toString();
		return "success";
	}
    
    public String fileUploadIMGroup() throws ServiceException {
    	logger.info("文件上传开始");
    	MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
    	file = req.getFiles("file")[0];
    	String groupId = ServletActionContext.getRequest().getParameter("groupId");
    	// 将文件拷贝到配置的目录
    	String newFile = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "/upload/groupImg/" + groupId + ".png";
    	try {
    		FileUtils.copyFile(file, new File(newFile));
    	} catch (IOException e) {
    		logger.error("拷贝文件失败 from:{},to{}", file.getAbsolutePath(), newFile);
    		logger.error(e.getMessage());
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_ERROR;
    	}
//		JSONObject j = new JSONObject();
//		StringBuffer url = req.getRequestURL();  
//		String tempContextUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();  
//		j.put("path", tempContextUrl +"/upload/"+fileDiskName);
//		jsonRes = j.toString();
    	jsonRes = "";
    	logger.info("上传文件名:{},文件大小:{}", fileName, fileSize);
    	return "success";
    }
    
    public String fileUploadIMHeadImg() throws ServiceException {
    	logger.info("文件上传开始");
    	MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
    	file = req.getFiles("file")[0];
    	String groupId = ServletActionContext.getRequest().getParameter("userId");
    	// 将文件拷贝到配置的目录
    	String newFile = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "/upload/headImg/" + groupId + ".jpg";
    	try {
    		FileUtils.copyFile(file, new File(newFile));
    	} catch (IOException e) {
    		logger.error("拷贝文件失败 from:{},to{}", file.getAbsolutePath(), newFile);
    		logger.error(e.getMessage());
    		rspCode = RtnCodeConstant.RTN_CODE_FILE_UPLOAD_ERROR;
    	}
//		JSONObject j = new JSONObject();
//		StringBuffer url = req.getRequestURL();  
//		String tempContextUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();  
//		j.put("path", tempContextUrl +"/upload/"+fileDiskName);
//		jsonRes = j.toString();
    	jsonRes = "";
    	logger.info("上传文件名:{},文件大小:{}", fileName, fileSize);
    	return "success";
    }

    private String getOtherCellsValue(int j, Row row, String[] cells) {
    	Cell cell = row.getCell(j);
		if (cell != null) {
			if (Cell.CELL_TYPE_NUMERIC == cell.getCellType() && org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
				cells[j] = DateUtil.formatDateTime(cell.getDateCellValue());
			} else {
				cell.setCellType(Cell.CELL_TYPE_STRING);
				cells[j] = StringUtils.trimToEmpty(cell.getStringCellValue());
			}
		}
		return cells[j];
	}

    public String getFileName() {
    	return fileName;
    }

    public File getFile() {
    	return file;
    }

    public String getFileSize() {
    	return fileSize;
    }

    public String getFileDiskName() {
    	return fileDiskName;
    }

    public void setFileDiskName(String fileDiskName) {
    	this.fileDiskName = fileDiskName;
    }

	public List<Map> getRows() {
		return rows;
	}

	public List getResultList() {
		return resultList;
	}

	public int getParticipants() {
		return participants;
	}

	public void setParticipants(int participants) {
		this.participants = participants;
	}

	public int getMeetDeptQty() {
		return meetDeptQty;
	}

	public void setMeetDeptQty(int meetDeptQty) {
		this.meetDeptQty = meetDeptQty;
	}

	public String getJsonRes() {
		return jsonRes;
	}

	public void setJsonRes(String jsonRes) {
		this.jsonRes = jsonRes;
	}

}
